package com.ruoyi.web.controller.gateway;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeOrderSettleModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.OpenApiRoyaltyDetailInfoPojo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Security;
import java.util.*;

/**
 * 功能描述
 *
 * @author: scott
 * @date: 2022年07月05日 15:15
 */
@Controller
@RequestMapping("/notify/")
public class NotifyController {

    @Resource
    private AlipayService alipayService;

    @Resource
    private ITRecipientInfoService recipientInfoService;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private ISysDictTypeService sysDictTypeService;

    @Resource
    private ITOrderInfoService orderInfoService;

    @Resource
    private ChargeService chargeService;

    @Resource
    private ITIsvInfoService itIsvInfoService;
    @Resource
    private ITMergeOrderDetailService itMergeOrderDetailService;

    @Resource
    private ITAliZftMerchantInfoService itAliZftMerchantInfoService;

    @Resource
    private ITPayChannelService payChannelService;

    @Resource
    private ISysUserService sysUserService;

    private static final Logger logger = LoggerFactory.getLogger(NotifyController.class);

    @ResponseBody
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "aliylpay/{orderCode}")
    @Log(title = "银联支付宝回调", businessType = BusinessType.NOTIFY)
    public Object forcePay(HttpServletRequest request, HttpServletResponse
            response,@PathVariable(value = "orderCode") String orderCode) throws Exception {
        Map requestParams = request.getParameterMap();
        //39.105.61.224
        String remoteIP = IpUtils.getIpAddr(request);
        String serverName = request.getRemoteHost();
        if (("39.105.61.224".indexOf(remoteIP) == -1) && ("39.105.61.224".indexOf(serverName) == -1)) {
            return new ErrorResponseData(-100, "ip无效！");

        }
        Map<String, String> params1 = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // try {
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"),
            // AlipayServiceEnvConstants.CHARSET);
            // } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            // }
            params1.put(name, valueStr);
        }
        logger.info("银联支付宝回调：{}",params1);

        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(Long.valueOf(orderCode));
        if (orderInfo == null) {
            logger.info("无记录或者订单已处理！");
            return new ErrorResponseData(-100, "无记录或者订单已处理！");
        }
        if(!params1.get("pay_status").toString().equals("1")){
            logger.info("非成功回调！");
            return new ErrorResponseData(-100, "非成功回调！");
        }
        TRecipientInfo recipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
        MsgPayResult msgPayResult = new MsgPayResult();
        msgPayResult.setChannel(orderInfo.getChannel());
        msgPayResult.setTradeNo(orderInfo.getId().toString());
        msgPayResult.setChannelAccount(recipientInfo.getChannelAccount());
        msgPayResult.setOrderId(orderInfo.getOutTradeNo());
        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getRealMoney() + ""));
        msgPayResult.setUid(recipientInfo.getUserId().toString());

        msgPayResult.setChannelPayMsgResult(JSON.toJSONString(params1));
        chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
        chargeService.notifyUserPaySucc(orderInfo.getId());
        logger.info("订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getRealMoney());
        return "success";
    }


//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/simplecreate")
//    @Log(title = "支付宝直付通服务商二级商户标准进件通知", businessType = BusinessType.NOTIFY)
//    public String simplecreateNotify(HttpServletRequest request, HttpServletResponse
//            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通服务商二级商户标准进件通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通服务商二级商户标准进件通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }
//
//
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/create")
//    @Log(title = "支付宝直付通二级商户创建通知", businessType = BusinessType.NOTIFY)
//    public String createNotify(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通二级商户创建通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通二级商户创建通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }
//
//
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/modify")
//    @Log(title = "支付宝直付通二级商户修改通知", businessType = BusinessType.NOTIFY)
//    public String modifyNotify(HttpServletRequest request, HttpServletResponse
//            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通二级商户修改通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通二级商户修改通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }
//
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/settlementmodify")
//    @Log(title = "支付宝直付通二级商户结算信息修改通知", businessType = BusinessType.NOTIFY)
//    public String settlementmodifyNotify(HttpServletRequest request, HttpServletResponse
//            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通二级商户结算信息修改通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通二级商户结算信息修改通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }
//
//
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/upgrade")
//    @Log(title = "支付宝直付通个人商户限额升级通知", businessType = BusinessType.NOTIFY)
//    public String upgradeNotify(HttpServletRequest request, HttpServletResponse
//            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通个人商户限额升级通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通个人商户限额升级通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }
//
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/notify/alizftpay/passed")
//    @Log(title = "支付宝直付通二级商户审核通过通知", businessType = BusinessType.NOTIFY)
//    public String passedNotify(HttpServletRequest request, HttpServletResponse
//            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
//        logger.info(String.format("支付宝直付通二级商户审核通过通知>>>>>>req{%s}", request));
//
//        //获取支付宝POST过来反馈信息
//        Map<String, String> params = new HashMap<>();
//        Map requestParams = request.getParameterMap();
//        logger.info("============================收到支付宝支付回调通知=====================================");
//
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用。
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//
//        }
//        logger.info("支付宝直付通二级商户审核通过通知:" + params);
//        String appCertPath = "/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
//        // 支付宝公钥证书路径
//        String alipayCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
//        // 支付宝根证书路径
//        String alipayRootCertPath = "/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";
//
//        // 支付宝网关
//        String serverUrl = "https://openapi.alipay.com/gateway.do";
//        // 应用APPID
//        String appId = "2021003196668931";
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                serverUrl,
//                appId,
//                appCertPath,
//                "RSA2",
//                alipayCertPath,
//                alipayRootCertPath,
//                "json");
////        String alipayPublicKey = tRealChannelConfig.getPublicKey();
//        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
//        boolean flag = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, "UTF-8", "RSA2");
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
//        if (flag == false) {
//            return "fail";
//        }
//        return "";
//    }

    @ResponseBody
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "alizft/{orderCode}")
    @Log(title = "支付宝直付通回调", businessType = BusinessType.NOTIFY)
    public Object alizftpayNotify(HttpServletRequest request, HttpServletResponse
            response,@PathVariable(value = "orderCode") String orderCode) throws Exception {
        Map requestParams = request.getParameterMap();
        //39.105.61.224
        String remoteIP = IpUtils.getIpAddr(request);
        String serverName = request.getRemoteHost();
        Map<String, String> params1 = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // try {
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"),
            // AlipayServiceEnvConstants.CHARSET);
            // } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            // }
            params1.put(name, valueStr);
        }
        logger.info("支付宝直付通回调：{}",params1);
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常

        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(Long.valueOf(orderCode));
        if (orderInfo == null) {
            logger.info("无记录或者订单已处理！");
            return new ErrorResponseData(-100, "无记录或者订单已处理！");
        }
        if(!params1.get("merge_pay_status").toString().equals("FINISHED")){
            logger.info("非成功回调！");
            return new ErrorResponseData(-100, "非成功回调！");
        }
        TIsvInfo tIsvInfo = itIsvInfoService.selectTIsvInfoById(Long.valueOf(orderInfo.getAliUserId()));
        AlipayClient alipayClient = getAliConfig(tIsvInfo);
        boolean flag = AlipaySignature.rsaCertCheckV1(params1, tIsvInfo.getIsvAliPublicPath(), "UTF-8", "RSA2");
        if (flag == false) {
            return "fail";
        }
////        boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
        String order_detail_results = params1.get("order_detail_results");
        JSONArray orderResultList = JSONArray.parseArray(order_detail_results);
        boolean isOk = true;
        for (int i = 0; i < orderResultList.size(); i++) {
            JSONObject detailObj = orderResultList.getJSONObject(i);
            if(detailObj.getString("trade_status").equals("TRADE_SUCCESS")){
                AlipayTradeOrderSettleRequest alipayTradeOrderSettleRequest = new AlipayTradeOrderSettleRequest();
                AlipayTradeOrderSettleModel model = new AlipayTradeOrderSettleModel();
                String out_request_no = UUID.getOrder();
                // 设置结算请求流水号
                model.setOutRequestNo(out_request_no);
                // 设置支付宝订单号
                model.setTradeNo(detailObj.getString("trade_no"));
                // 设置分账明细信息
                TMergeOrderDetail mergeOrderDetail = new TMergeOrderDetail();
                mergeOrderDetail.setOutTradeNo(detailObj.getString("out_trade_no"));
                mergeOrderDetail = itMergeOrderDetailService.selectTMergeOrderDetailList(mergeOrderDetail).get(0);
                TAliZftMerchantInfo tAliZftMerchantInfo = itAliZftMerchantInfoService.selectTAliZftMerchantInfoById(Long.valueOf(mergeOrderDetail.getSubMerId()));
                List<OpenApiRoyaltyDetailInfoPojo> royaltyParameters = new ArrayList<OpenApiRoyaltyDetailInfoPojo>();
                OpenApiRoyaltyDetailInfoPojo royaltyParameters0 = new OpenApiRoyaltyDetailInfoPojo();
                royaltyParameters0.setRoyaltyType("transfer");
                royaltyParameters0.setTransInType("loginName");
                royaltyParameters0.setTransIn(tAliZftMerchantInfo.getAlipayLogonId());
                BigDecimal money1 = new BigDecimal(mergeOrderDetail.getPayRate()*orderInfo.getMoney()).divide(new BigDecimal(100)).divide(new BigDecimal(100)).setScale(2);

                royaltyParameters0.setAmount(money1.toString());
                royaltyParameters0.setDesc("分账给"+tAliZftMerchantInfo.getAlipayLogonId());
                royaltyParameters.add(royaltyParameters0);
                model.setRoyaltyParameters(royaltyParameters);

                alipayTradeOrderSettleRequest.setBizModel(model);
                AlipayTradeOrderSettleResponse alipayTradeOrderSettleResponse = alipayClient.execute(alipayTradeOrderSettleRequest);
                logger.info(alipayTradeOrderSettleResponse.getBody());
                if (alipayTradeOrderSettleResponse.isSuccess()) {
                    isOk = false;
                } else {
                    isOk = false;
                    // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                    // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                    // logger.info(diagnosisUrl);
                }
            }
        }
        //分账
        if(isOk){
            TRecipientInfo recipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
            MsgPayResult msgPayResult = new MsgPayResult();
            msgPayResult.setChannel(orderInfo.getChannel());
            msgPayResult.setTradeNo(orderInfo.getId().toString());
            msgPayResult.setChannelAccount(recipientInfo.getChannelAccount());
            msgPayResult.setOrderId(orderInfo.getOutTradeNo());
            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getRealMoney() + ""));
            msgPayResult.setUid(recipientInfo.getUserId().toString());
            msgPayResult.setChannelPayMsgResult(JSON.toJSONString(params1));
            chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
            chargeService.notifyUserPaySucc(orderInfo.getId());

            logger.info("订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getRealMoney());
        }else{
            logger.info("订单回调..订单号：" + orderInfo.getId() + " 执行退款动作：" + orderInfo.getRealMoney());
            //执行退款动作
            AlipayTradeRefundRequest alipayTradeRefundRequest = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            String out_request_no = UUID.getOrder();
            // 设置商户订单号
            model.setOutTradeNo(orderCode);
            // 设置退款金额
            model.setRefundAmount(MoneyUtil.fenToYuan(orderInfo.getRealMoney() + ""));
            // 设置退款原因说明
            model.setRefundReason("正常退款");
            alipayTradeRefundRequest.setBizModel(model);
            AlipayTradeRefundResponse alipayTradeRefundResponse = alipayClient.execute(alipayTradeRefundRequest);
            logger.info(alipayTradeRefundResponse.getBody());

            if (alipayTradeRefundResponse.isSuccess()) {
                logger.info("调用成功");
            } else {
                logger.info("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // logger.info(diagnosisUrl);
            }
        }

        return "success";
    }


    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/alizftpay/passed")
    @Log(title = "支付宝直付通应用通知", businessType = BusinessType.NOTIFY)
    public String appNotify(HttpServletRequest request, HttpServletResponse
            response) throws UnsupportedEncodingException, InterruptedException, AlipayApiException {
        logger.info(String.format("支付宝直付通应用通知>>>>>>req{%s}", request));

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        logger.info("============================收到支付宝直付通应用通知=====================================");

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);

        }
        logger.info("支付宝直付通二级商户通知:" + params);
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());//解决 no such provider: BC异常
        if(params.get("method").equalsIgnoreCase("ant.merchant.expand.indirect.zft.passed")){
            //支付宝直付通二级商户审核通过通知
            String biz_content = params.get("biz_content");
            JSONObject bizObj = JSONObject.parseObject(biz_content);
            String orderId = bizObj.getString("order_id");
            TAliZftMerchantInfo tAliZftMerchantInfo = new TAliZftMerchantInfo();
            tAliZftMerchantInfo.setOrderId(orderId);
            List<TAliZftMerchantInfo> tAliZftMerchantInfos = itAliZftMerchantInfoService.selectTAliZftMerchantInfoList(tAliZftMerchantInfo);
            tAliZftMerchantInfo = tAliZftMerchantInfos.get(0);
            TIsvInfo tIsvInfo = itIsvInfoService.selectTIsvInfoById(Long.valueOf(tAliZftMerchantInfo.getIsvId()));
//            AlipayClient alipayClient = getAliConfig(tIsvInfo);
            boolean flag = AlipaySignature.rsaCertCheckV1(params, tIsvInfo.getIsvAliPublicPath(), "UTF-8", "RSA2");
            if (flag == false) {
                return "fail";
            }
            tAliZftMerchantInfo.setSmid(bizObj.getString("smid"));
            tAliZftMerchantInfo.setMessage(biz_content);
            //审核通过
            tAliZftMerchantInfo.setStatus(1);
            itAliZftMerchantInfoService.updateTAliZftMerchantInfo(tAliZftMerchantInfo);
            //审核通过添加到收款列表
            TRecipientInfo tRecipientInfo = new TRecipientInfo();
            tRecipientInfo.setChannelType("alipay");
            tRecipientInfo.setCreateTime(DateUtils.getNowDate());
            tRecipientInfo.setChannelAccount(bizObj.getString("smid"));
            tRecipientInfo.setChannelDisabled(0);
            tRecipientInfo.setAvailable(1);
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setNeedOnline(1);
            TPayChannel payChannelParam = new TPayChannel();
            payChannelParam.setChannel("isv_alipay_zft");
            TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
            tRecipientInfo.setNeedOnline(orderChannel.getNeedOnLine());
            tRecipientInfo.setLoginType(orderChannel.getLoginType());
            if(ObjectUtil.isNotEmpty(tRecipientInfo.getPassWord())){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("password",tRecipientInfo.getPassWord());
                tRecipientInfo.setAccountJson(jsonObject.toJSONString());
            }
            if(ObjectUtil.isNotEmpty(tRecipientInfo.getYlKey())){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ylKey",tRecipientInfo.getYlKey());
                tRecipientInfo.setAccountJson(jsonObject.toJSONString());
            }
            if(ObjectUtil.isEmpty(tRecipientInfo.getShopNickname())){
                tRecipientInfo.setShopNickname(null);
            }
            if(ObjectUtil.isEmpty(tRecipientInfo.getShopClerkAccount())){
                tRecipientInfo.setShopClerkAccount(null);
            }
            if(tRecipientInfo.getChannel().equals("card_to_card")){
                if(tRecipientInfo.getBankName().contains("邮储")){
                    tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-3, tRecipientInfo.getCardNo().length()));
                }else{
                    tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-4, tRecipientInfo.getCardNo().length()));
                }
            }
            if(tRecipientInfo.getChannel().startsWith("isv_alipay")){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("aliPublicPath",tIsvInfo.getIsvAliPublicPath());
                jsonObject.put("aliPrivateKey",tIsvInfo.getIsvAliPrivateKey());
                jsonObject.put("appPublicPath",tIsvInfo.getIsvAppPublicPath());
                jsonObject.put("aliRootPath",tIsvInfo.getIsvAliRootPath());
                tRecipientInfo.setAccountJson(jsonObject.toJSONString());
            }
            tRecipientInfo.setUserId(ShiroUtils.getUserId());
            recipientInfoService.insertTRecipientInfo(tRecipientInfo);

        } else if (params.get("msg_method").equalsIgnoreCase("aant.merchant.expand.indirect.zft.rejected")) {
            //支付宝直付通二级商户审核失败通知
            String biz_content = params.get("biz_content");
            JSONObject bizObj = JSONObject.parseObject(biz_content);
            String orderId = bizObj.getString("order_id");
            TAliZftMerchantInfo tAliZftMerchantInfo = new TAliZftMerchantInfo();
            tAliZftMerchantInfo.setOrderId(orderId);
            List<TAliZftMerchantInfo> tAliZftMerchantInfos = itAliZftMerchantInfoService.selectTAliZftMerchantInfoList(tAliZftMerchantInfo);
            tAliZftMerchantInfo = tAliZftMerchantInfos.get(0);
            tAliZftMerchantInfo.setSmid(bizObj.getString("smid"));
            tAliZftMerchantInfo.setMessage(biz_content);
            tAliZftMerchantInfo.setStatus(2);
            itAliZftMerchantInfoService.updateTAliZftMerchantInfo(tAliZftMerchantInfo);
        }
        return "success";
    }

    private AlipayClient getAliConfig(TIsvInfo isvInfo) throws AlipayApiException {
        String appCertPath = isvInfo.getIsvAppPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
        // 支付宝公钥证书路径
        String alipayCertPath = isvInfo.getIsvAliPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
        // 支付宝根证书路径
        String alipayRootCertPath = isvInfo.getIsvAliRootPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";

        // 应用APPID
        String appId = isvInfo.getIsvAppId();//"2021003196668931";
        // 初始化SDK
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
//        certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYjCsmZsld84YkTStL/AATrGzCmSLb6J4FZGV4eYSZWdGhsPDf3XEzCMTL/g3WvDNIISGiVek2NYXGKqy6VMdKHoS+miypmJVZ3EkgPwj/0hJWeyrKvWFn1nIUeW8u7mnJ7KJl51Opaj/+RUtkGWHKxOrBCY5KT2q7hiUTszuLCt23muU8dF9nxL9Kc+x6NgtPhj/oGdJNgQZMdjBqvshZ06oVoHcWDzK+zJJmft4YI+Km1+Uvcyk5ZtPDFXaqeFuSCUPBdRHq9AdoUG/CW1Xy0xVcICAZnI0SzuhKH9eEhyuLQ8yKHp8kajzXTxCUgKU5qI8wQmI2YiupVdQ+HqhDAgMBAAECggEAUcxnnvHi7HQW7ARNQTNhvyroLvj6jj0P7whEuPNAPRLCrBc7Mm+Fsb3z+QbD2O+V+Al8BZZXtW/Byd88O7YWHxJ6T9JQPKjK/SJ4O8hRRQwaNTFaYthmEM4W4g+zpNDG/TXcZxRB8kg9BFWX9Zb+r0IkN1quZ/5p1yA5ZXToaseW53da2N7TESXvrEGj4wQ91iHbRKVkCQGJBOPWuxKvmwU8h1NzpvQ4c1O/ZTuOmYzdBpNOVmNh5po1UGOkBYAMudh04X1CNBiSMkhrORe7Pw3grrOSyARSfutvQthww/xQ4JqHpi353gCPXwl22PXjUBRwXRKvaZM43w7h85vC4QKBgQDHSGI3j8Fes+HNhb/PXTETG1e4BFH1XQJgGXICOe5f4+Yi7Ih5KJrUu5xpD95/lYHqfnkXJhAzKFhcnCN8/3pol9af1WZU74XPjVmhE5pm1NoBjxqTFiS4g74TsGrCr3meE7C0fHuEL50LEJ+gzUhynKqjbir/j2fzHw/BiLYOKwKBgQDD9q+1aMsZ4QA1Xohu9bXHP2rD7UZzvrqD06rjEFuKnRWcob5afADKwx/wvlMucARPHMGMy/4uoBlDE5cLVRcFgq0Id2JiO9JpBWLJBMeEWKpF5ql9fEjayRiunaSt0rMKc6jjVfZxOOGrSdGlhZfjT9kwJpkyGtu5RhrhwGzaSQKBgG0twemQz68TvBT+PtzbwKQoKcG+VCyp/UArEKQZmvhcAlyF3CsMzO7ZrlJ9CDg778ZJ7gt5pgxxASATxvmXejfNYB+HKZ5E77mLRlySQdguqxWJklSdIBcazks5LvRkcKvjO79WJ9F+yHokbGALt7JbFL2fAN2scpXnIZm1TZCrAoGBAKqIWpA8CcMTkuLeyUwGd5JVFcw7CDxhll5yLRw8d+1AljYga07C6s2I0Jroheq7gIR4OdcVDrX0jQdaXO93tPkOpxXfDrb96DWMglL83cPGhScffA+/wIbkyZ3rggvid/x4elibzkLphTlSnCa3A17FdfP5Iwf/Z4bsAyjCE/hBAoGAP3e6umlHA/YSvULwK8W+5+CSql8tfMcycn7+IzZb8x4E5mwMERyViUBPTtLD+96HpLvNgiCtGTi+N0i0xa3mxyrOJwIvnKawCrHjO44wrtW59XLD6Ns8J2VxW9BYuGNFJ7SU+PXJ5nVNhdC9USLs9B7agLOJ9mOmNWCRuW1Jvrs=");
        certAlipayRequest.setPrivateKey(isvInfo.getIsvAliPrivateKey());

        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }

    /**
     * 支付宝支付成功结果回调通知
     * @return
     */
    @RequestMapping(value = "/alipay/notifySucc",method = RequestMethod.POST)
    public void callback(HttpServletRequest request, HttpServletResponse response) {


        try{
            logger.info(String.format("收到支付宝支付成功回调>>>>>>req{%s}", request));

            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();
            logger.info("============================收到支付宝支付回调通知=====================================");

            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                logger.info("name="+name+",value="+valueStr);
                params.put(name, valueStr);

            }
            // 获取订单
            Long orderId = Long.valueOf(params.get("out_trade_no"));
            TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);

            long recipientId = orderInfo.getRecipientId();
            TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(recipientId);

            // 获取支付宝公钥

            JSONObject jsonObject = JSON.parseObject(userRecipientInfo.getAccountJson());
            String alipayPublicKey = jsonObject.getString("aliPublicKey");

            boolean flag = alipayService.checkPayResult(alipayPublicKey,params);
            // 非法通知
            if(flag == false){
                logger.info("非法的回调通知！！！！！");
                return;
            }
        /*
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（
        有的时候，一个商户可能有多个seller_id/seller_email），
        4、验证app_id是否为该商户本身。
        上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
        在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
        在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。

        */
            String appId =userRecipientInfo.getChannelAccount();
            boolean checkAppId = alipayService.checkAppId(params.get("app_id"),appId);
            if(checkAppId==false){
                logger.info("非法的回调通知，appId不正确！！！");
                return;
            }
        /*boolean checkSellerEmail = alipayService.checkSellerEmail(params.get("seller_email"));
        if(checkSellerEmail==false){
            log.warn("非法的回调通知，sellerEmail不正确！！！");
            return;
        }*/
            String trade_status = params.get("trade_status");
            if(!trade_status.equals("TRADE_SUCCESS") && !trade_status.equals("TRADE_FINISHED")){
                logger.info("用户支付不成功的回调通知！！！！！");
                return;
            }
            // 单位元转成分
            String yMoney = params.get("total_amount");
            Long totalAmount = MoneyUtil.yuanToFen(yMoney);


            //body 参数
       /* Gson gson = new Gson();
        Map<String,Object> bodyMap = gson.fromJson(params.get("body"),Map.class);
        int orderTypeValue = Double.valueOf(String.valueOf(bodyMap.get("orderType"))).intValue();*/

            //订单金额不匹配
            if(totalAmount.longValue() != orderInfo.getRealMoney()){
                logger.info(String.format("订单金额不匹配！！！！！callback=%d,our=%d",
                        totalAmount,orderInfo.getRealMoney()));
                return;
            }
            // ------------------所有校验都通过准备进行相关业务操作----------------------//
            logger.info("回调通知校验成功！准备进行相关业务操作...");

            // 判断现金红包，需要发起领红包接口

            MsgPayResult msgPayResult = new MsgPayResult();
            msgPayResult.setChannel(orderInfo.getChannel());
            msgPayResult.setTradeNo(params.get("trade_no"));
            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
            msgPayResult.setOrderId(orderId.toString());
            msgPayResult.setRealMoney(yMoney);
            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
            msgPayResult.setBillTime(params.get("gmt_payment"));
            msgPayResult.setChannelPayMsgResult(JSON.toJSONString((params)));
            chargeService.updateOrderPayResult(false,orderId,msgPayResult,false);
            chargeService.notifyUserPaySucc(orderInfo.getId());

            logger.info("============================回调通知处理完毕=====================================");
            response.getWriter().println("success");
        }catch (Exception e){
            logger.error("支付宝回调处理失败：{}",e.getMessage());
            try {
                response.getWriter().println("no");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }



    @RequestMapping(value = "/gamepay/notifySucc",method = RequestMethod.POST)
    public void gamepayCallBack(HttpServletRequest request, HttpServletResponse response) {


        try{
            logger.info(String.format("收到gamepay支付成功回调>>>>>>req{%s}", request));

            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();

            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                logger.info("name="+name+",value="+valueStr);
                params.put(name, valueStr);

            }
            // 获取订单
            Long orderId = Long.valueOf(params.get("out_trade_no"));
            TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);

            long recipientId = orderInfo.getRecipientId();
            TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(recipientId);

            // 获取支付宝公钥

            JSONObject jsonObject = JSON.parseObject(userRecipientInfo.getAccountJson());
            String key = jsonObject.getString("key");

            String sign = params.remove("sign");
            StringBuilder buf = new StringBuilder("");
            SignUtils.buildPayParams(buf, params, false, "low");
            String preStr = buf.toString();
            logger.info("参数排序==>待验签数据:" + preStr);
            String signTmp = MD5Util.stringMD5(preStr+ "&key=" + key);

            // 非法通知
            if(!signTmp.equalsIgnoreCase(sign)){
                logger.info("非法的回调通知！！！！！");
                return;
            }

            String trade_status = params.get("orderStatus");
            if(!trade_status.equals("1")){
                logger.info("用户支付不成功的回调通知！！！！！");
                return;
            }
            String yMoney = params.get("totalAmount");
            Long totalAmount = Long.valueOf(yMoney);
            //订单金额不匹配
            if(totalAmount.longValue() != orderInfo.getRealMoney()){
                logger.info(String.format("订单金额不匹配！！！！！callback=%d,our=%d",
                        totalAmount,orderInfo.getRealMoney()));
                return;
            }
            // ------------------所有校验都通过准备进行相关业务操作----------------------//
            logger.info("回调通知校验成功！准备进行相关业务操作...");

            // 判断现金红包，需要发起领红包接口

            MsgPayResult msgPayResult = new MsgPayResult();
            msgPayResult.setChannel(orderInfo.getChannel());
            msgPayResult.setTradeNo(params.get("tradeNo"));
            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
            msgPayResult.setOrderId(orderId.toString());
            msgPayResult.setRealMoney(yMoney);
            msgPayResult.setUid(userRecipientInfo.getUserId().toString());

            msgPayResult.setChannelPayMsgResult(JSON.toJSONString((params)));
            chargeService.updateOrderPayResult(false,orderId,msgPayResult,false);
            chargeService.notifyUserPaySucc(orderInfo.getId());

            logger.info("============================回调通知处理完毕=====================================");
            response.getWriter().println("success");
        }catch (Exception e){
            logger.error("GAME回调处理失败：{}",e.getMessage());
            try {
                response.getWriter().println("no");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }



    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "/callback/v2/{serviceName}/{orderCode}")
    public @ResponseBody Object paymentV2Notify(HttpServletRequest request, HttpServletResponse
            response, @PathVariable("serviceName") String serviceName, @PathVariable(value = "orderCode") long orderCode) throws
            Exception {
        TOrderInfo tPaymentOrder = orderInfoService.selectTOrderInfoById(orderCode);
        PayNotifyInterface payNotifyInterface;
        if (tPaymentOrder == null) {
            return new ErrorResponseData(-100, "获取订单失败！");
            
        }
        logger.info(tPaymentOrder.getId() + "=====paymentNotify=====" + tPaymentOrder.getStatus());
        logger.info("=====回调时订单状态=====" + tPaymentOrder.getStatus());
        TRecipientInfo tRealChannelConfig = recipientInfoService.selectTRecipientInfoById(tPaymentOrder.getRecipientId());
        JSONObject returnObject = JSONObject.parseObject(tRealChannelConfig.getReturnJson());
        String callBackIp = returnObject.getString("callBackIp");


        SysUser sysUser = sysUserService.selectUserById(tPaymentOrder.getUserId());

        logger.info("回调通道名称===" + serviceName);
        if (tPaymentOrder.getPaySucc()==1) {
//            itPaymentOrderService.doNotify(tPaymentOrder);
            logger.info(tPaymentOrder.getId() + "=====订单已处理=====" );

            return returnObject.getString("returnMsg");
        }
//        String orderStatusRs = checkOrderStatus(tPaymentOrder);
//        if(orderStatusRs.equalsIgnoreCase("fail")){
//            return "fail";
//        }
        Map requestParams = request.getParameterMap();
        String remoteIP = IpUtils.getIpAddr(request);
        String serverName = request.getRemoteHost();

        Map<String, Object> params1 = new HashMap<String, Object>();
        Map<String, Object> allparams = new HashMap<String, Object>();
        String notifyRequestType = returnObject.getString("notifyRequestType");
        logger.info("==读取方式======" + returnObject.getString("notifyRequestType"));
        if (notifyRequestType.equalsIgnoreCase("ParameterMap")) {
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {


                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";

                }
                // 乱码解决，这段代码在出现乱码时使用。
                // try {
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"),
                // AlipayServiceEnvConstants.CHARSET);
                // } catch (UnsupportedEncodingException e) {
                // e.printStackTrace();
                // }

                String isNeedUrlEncode = returnObject.getString("isNeedUrlEncode");
                if (StringUtils.isNotBlank(isNeedUrlEncode) && isNeedUrlEncode.equalsIgnoreCase("true")) {
                    allparams.put(name, URLEncoder.encode(valueStr));

                } else {
                    allparams.put(name, valueStr);

                }
            }
            if (StringUtils.isNotBlank(returnObject.getString("callbackObjKey"))) {
                String callbackStr = allparams.get(returnObject.getString("callbackObjKey")).toString();
                params1 = JSON.parseObject(callbackStr, Map.class);
            } else {
                params1 = allparams;
            }
        } else if (notifyRequestType.equalsIgnoreCase("InputStream")) {
            BufferedReader br;
            StringBuilder sb = null;
            String reqBody = null;
            br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
//            body = URLDecoder.decode(body, "UTF-8").replace("}=", "}");
            logger.info("==采用流的方式獲取到的======" + reqBody);
            //            logger.info("==采用RequestBody獲取到的======" + body);
            if (StringUtils.isBlank(reqBody)) {
                logger.info("==无回调参数======" );
                return "fail";
            }
            params1 = JSON.parseObject(reqBody, Map.class);
            params1.put("responStr", reqBody);
        }
        logger.info(serviceName + "回调进来了============params:" + params1);
        if (params1.size() == 0) {
            logger.info("==无回调参数======" );
            return "fail";
        }
        if (StringUtils.isNotBlank(callBackIp)) {
            logger.info("配置的回调IP: " + callBackIp + " 接收回调IP===" + remoteIP + " serverName:" + serverName);
            if ((callBackIp.indexOf(remoteIP) == -1) && (callBackIp.indexOf(serverName) == -1)) {

                logger.info("==非法回调IP======" );
                return "fail";
            }
        }
        try {
            payNotifyInterface = (PayNotifyInterface) SpringUtils.getBean(serviceName.toLowerCase() + "PayNotifyService");
        } catch (BeansException e) {
            logger.info(e.getMessage());
            logger.info("支付渠道类型[channel=" + serviceName + "]实例化异常");
            return "fail";
        }
        JSONObject retObj = payNotifyInterface.doNotify(tPaymentOrder, tRealChannelConfig, params1, request);
        if (retObj.getString("resCode").equals("fail")) {
            return "fail";
        } else {
            return returnObject.getString("returnMsg").replace("0x99orderCode", tPaymentOrder.getId()+"");
        }
    }

}
